# author: wuye
# describe: 这是一个gitee的webhook用法（当一个PR被合并时，可以执行一些其它操作）
import base64
import hmac
import hashlib
import logging
import platform
from datetime import datetime, timedelta, timezone
from logging.handlers import RotatingFileHandler
from subprocess import check_output

import pytz

from flask import Flask, request, jsonify


class MyLogging:
    def __init__(self, filename):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)
        if not self._check_shanghai_time:  # 如果时区不是中国时区，则把时间转为中国时区
            logging.Formatter.converter = self._beijing

        # fh = logging.FileHandler(filename=filename, mode="a", encoding="utf-8")
        fh = RotatingFileHandler(filename=filename, maxBytes=10 * 1024 * 1024, backupCount=5,
                                 encoding="utf-8")  # 每个日志文件10M大小, 超出大小生成5个备份文件
        fm = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s: %(message)s")
        self.logger.addHandler(fh)
        fh.setFormatter(fm)

        # sh = logging.StreamHandler()  # 创建一个屏幕操作符
        # self.logger.addHandler(sh)
        # sh.setFormatter(fm)

    def _check_shanghai_time(self):
        return datetime.now().astimezone().tzinfo == timezone(timedelta(hours=8))

    def _beijing(self):
        return datetime.now(pytz.timezone("Asia/Shanghai")).timetuple()

    def get_log(self):
        return self.logger


if platform.system() == "Linux":
    log = MyLogging("/var/log/git_webhook/gitee_webhook.log")
    # log = MyLogging("./gitee_webhook.log")
else:
    log = MyLogging("./gitee_webhook.log")

logger = log.get_log()

app = Flask(__name__)


def get_sign(timestamp):
    secret = 'this is secret'
    string_to_sign = "{}\n{}".format(timestamp, secret)
    ret = hmac.new(secret.encode("utf-8"), string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
    sign = base64.b64encode(ret).decode("utf-8")
    return sign


@app.route("/gitee_webhook", methods=["POST"])
def main():
    data = request.json
    timestamp = request.args.get("timestamp")
    git_token = request.headers.get("X-Gitee-Token")
    sign = get_sign(timestamp)
    if git_token != sign:
        logger.warning("校验失败")
        return jsonify({"status": "Failed", "reason": "Verification failed"})
    pr_data = data.get("pull_request")
    if not pr_data:
        return jsonify({"status": "Failed", "reason": "Data error."})
    pr_state = pr_data.get("state", "")   # open merged
    pr_title = pr_data.get("title", "")
    pr_merged = pr_data.get("merged", False)
    pr_merged_at = pr_data.get("merged_at", "-1")
    msg = f"来自PR的消息：当前PR的title是：{pr_title}, 当前PR的状态是：{pr_state}, PR的合并状态为：{pr_merged}, PR的合并时间为：{pr_merged_at}"
    logger.info(msg)
    try:
        # 当发现PR合并后执行build动作
        if pr_state == "merged" and pr_merged is True:
            command_build = ["bash", "/opt/build_blog.sh"]
            output_build = check_output(command_build).decode()
            logger.info(f"output_build: {output_build}")
    except Exception as e:
        logger.error(e)
        return jsonify({"status": "Failed", "reason": "Run command failed!"})
    return jsonify({"status": "OK", "reason": ""})


if __name__ == '__main__':
    app.run("0.0.0.0", 10000)
